#include "stdafx.h"
#include "HistoryIndicatorGoods.h"
#include "DataManager.hpp"
#include "HistoryIndicator.h"
#include "HistoryGlobal.h"
#include "HistoryLayout.h"
#include "KLineMain.h"
#include "ColorData.h"

CHistoryIndicatorGoods::CHistoryIndicatorGoods(SGHandle owner_handle) : CHistoryIndicatorBase(owner_handle)
{
}

CHistoryIndicatorGoods::~CHistoryIndicatorGoods()
{
    if(m_pData) {
        m_pData->onDataUpdate.disconnect(boost::bind(&CHistoryIndicatorGoods::OnDataUpdate, this));
    }
}

#pragma region SG Message

BOOL CHistoryIndicatorGoods::OnSGInitContext( SGContext* context_param )
{
    int goods = context_param->lparam;
	int goods_index = context_param->param1;
    m_nGoods = goods;
	m_nGoodsIndex = goods_index;

	return TRUE;
}

BOOL CHistoryIndicatorGoods::OnSGGoodsChange( SGGoodsChange* goods_change_param )
{
	CPeriodType period(goods_change_param->period_type, goods_change_param->period_param);
	CHistoryData::Key key(m_nGoods, period);

	if(m_pData && key == m_pData->m_tKey) {
		return FALSE;
	}

    if(m_pData) {
        m_pData->onDataUpdate.disconnect(boost::bind(&CHistoryIndicatorGoods::OnDataUpdate, this));
    }

	m_pData = CDataManager<CHistoryData>::Instance()->GetData(key);
	m_pData->onDataUpdate.connect(boost::bind(&CHistoryIndicatorGoods::OnDataUpdate, this));

	CHistoryIndicator* indicator_ptr = (CHistoryIndicator*)owner_handle_;
	uint64_t valid_begin_time = indicator_ptr->GetView()->GetLayout()->GetValidBeginTime();
	m_pData->LoadDataByRange(valid_begin_time);

    return FALSE;
}

BOOL CHistoryIndicatorGoods::OnSGSyncData( SGRange<uint64_t>* range_param)
{
	if(m_pData) {
		m_pData->SyncDataByRange(range_param->begin, range_param->end);
	}

	return FALSE;
}

BOOL CHistoryIndicatorGoods::OnSGDrawBack( SGCanvas* canvas_param )
{
	CKLineMain kline;
	CHistoryIndicator* indicator_ptr = (CHistoryIndicator*)owner_handle_;
	CAxes& axes = indicator_ptr->GetAxes();

	kline.SetType(SGIndicator::SG_GOODS_CANDLE);
	kline.SetData(m_pData);

	CColorData::Key key(SGIndicator::SG_COLOR_GOODS, m_nGoodsIndex);
	std::shared_ptr<CColorData> data_ptr = CDataManager<CColorData>::Instance()->GetData(key);

	kline.SetColor(data_ptr->GetColor());
	kline.Draw(axes, canvas_param);

	return FALSE;
}

BOOL CHistoryIndicatorGoods::OnSGDrawFore( SGCanvas* canvas_param )
{
	return FALSE;
}

#pragma endregion SG Message

#pragma region SG Event

void CHistoryIndicatorGoods::OnDataUpdate()
{
	CHistoryIndicator* indicator_ptr = (CHistoryIndicator*)owner_handle_;
	indicator_ptr->GetView()->GetLayout()->UpdateBack();
}

#pragma endregion SG Event
